package com.itheima.reggie.controller;

import com.itheima.reggie.entity.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.util.SMSUtils;
import com.itheima.reggie.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired(required = false)
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        String code = "1234";
        // String code = ValidateCodeUtils.generateValidateCode4String(4);
        // SMSUtils.sendMessage("黑马旅游网", "SMS_205126318", user.getPhone(), code);

        //用手机号码作键储存验证码
        // session.setAttribute(user.getPhone(), code);
        redisTemplate.opsForValue().set(user.getPhone(), code, 1, TimeUnit.MINUTES);
        log.info("验证码：" + code);

        return R.success("发送成功");
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map<String, String> map, HttpSession session) {
        //获得用户输入的手机号码和验证码
        String phone = map.get("phone");
        String code = map.get("code");

        //从session中获取系统的验证码
        // String verifyCode = (String) session.getAttribute(phone);
        String verifyCode = (String) redisTemplate.opsForValue().get(phone);

        User user = userService.login(phone, code, verifyCode);
        if (user == null) {
            return R.error("验证码错误");
        }

        session.setAttribute("user", user.getId());

        return R.success(user);

    }

    @PostMapping("/loginout")
    public R<String> loginout(HttpSession session) {

        session.invalidate();
        return R.success("bye");

    }
}
